package flink.yarn;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;

import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JasonLee
 * @description 获取yarn队列上面任务的状态信息
 * @date $date$ $time$
 */
public class YarnClientUtils {
    private static final YarnClient yarnClient;

    static {
        Configuration conf = new YarnConfiguration();
        yarnClient = YarnClient.createYarnClient();
        yarnClient.init(conf);
        yarnClient.start();
    }

    /**
     * 获取 Yarn 上正在运行的任务
     *
     * @return 返回 Yarn 上正在运行的任务的集合
     * @throws IOException 抛出异常
     * @throws YarnException 抛出异常
     */
    public static Map<String, ApplicationReport> getApplicationReport()
            throws IOException, YarnException {
        Map<String, ApplicationReport> map = new HashMap<>(1000);
        // 获取running状态任务的集合
        List<ApplicationReport> applications =
                yarnClient.getApplications(EnumSet.of(YarnApplicationState.RUNNING));
        for (ApplicationReport applicationReport : applications) {
            map.put(applicationReport.getName(), applicationReport);
        }
        return map;
    }
    /**
     * 判断任务是否挂了
     *
     * @param applicationId 传入任务的 id
     * @return 返回 true/false
     */
    public static boolean isDown(ApplicationId applicationId) {
        try {
            ApplicationReport applicationReport = yarnClient.getApplicationReport(applicationId);
            YarnApplicationState yarnApplicationState = applicationReport.getYarnApplicationState();
            if (YarnApplicationState.FINISHED.equals(yarnApplicationState)) {
                return true;
            }
        } catch (YarnException | IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据 applicationId 删除任务
     *
     * @param applicationId 任务的 id
     * @throws IOException 抛出异常
     * @throws YarnException 抛出异常
     */
    public static void deleteApplication(ApplicationId applicationId)
            throws IOException, YarnException {
        yarnClient.killApplication(applicationId);
    }
}
